package com.hspedu.homework;

import java.util.Scanner;

/**
 * @Author Stringzhua
 * @Date 2024/3/15 17:38
 * description:
 * 1.在main方法中,启动两个线程
 * 2.第1个线程中循环随机打印100以内的整数
 * 3.直到第2个线程从键盘读取了"Q"命令
 */
public class homework01 {
    public static void main(String[] args) {
        S1 s1 = new S1();
        S2 s2 = new S2(s1);
        s1.start();
        s2.start();
    }
}

//第1个线程中循环随机打印100以内的整数
class S1 extends Thread {
    private boolean loop = true;

    @Override
    public void run() {
        while (loop) {
            System.out.println((int) (Math.random() * 100 + 1));
            try {
                Thread.sleep(1000);//休眠1s
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("S1线程退出。。。");
    }

    public void setLoop(boolean loop) {//通过Set方法修改loop变量
        this.loop = loop;
    }
}

//直到第2个线程从键盘读取了"Q"命令
class S2 extends Thread {
    private S1 s1;
    private Scanner scanner = new Scanner(System.in);

    public S2(S1 s1) {
        this.s1 = s1;
    }

    @Override
    public void run() {
        while (true) {
            //接收到用户输入
            System.out.println("请输入你的指令(Q)表示退出");
            char key = scanner.next().toUpperCase().charAt(0);
            if (key == 'Q') {
                //以通知的方式结束S1线程
                s1.setLoop(false);
                System.out.println("S2线程退出。。。");
                break;
            }
        }
    }
}